package com.jh.fcsm.common.handler;

import com.jh.fcsm.beans.sys.vo.ResponseInfo;
import com.jh.fcsm.common.RestApiResponse;
import com.jh.fcsm.common.exception.BaseException;
import com.jh.fcsm.common.exception.ServiceException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@ControllerAdvice("com.jh.fcsm")
@ResponseBody
public class GlobalExceptionHandler {
    private final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    public GlobalExceptionHandler() {
    }

    @ExceptionHandler(BaseException.class)
    public ResponseInfo baseExceptionHandler(HttpServletResponse response, BaseException ex) {
        logger.error(ex.getMessage());
        response.setStatus(500);
        return new ResponseInfo(ex.getStatus() + "", ex.getMessage());
    }

    @ExceptionHandler(ServiceException.class)
    public RestApiResponse<?> baseExceptionHandler(HttpServletResponse response, ServiceException ex) {
        logger.error(ex.getMessage());
        response.setStatus(200); //ServiceException返回200
        return RestApiResponse.error(ex.getMessage());
    }

    @ExceptionHandler(AccessDeniedException.class)
    public ResponseInfo accessDeniedExceptionHandler(HttpServletResponse response, Exception ex) {
        response.setStatus(403);
        logger.error(ex.getMessage());
        return new ResponseInfo(403 + "", "api无权限");
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public RestApiResponse<?> otherExceptionHandler(HttpServletResponse response, MethodArgumentNotValidException ex) {
        response.setStatus(500);
        logger.error("Validation error: ", ex);

        BindingResult bindingResult = ex.getBindingResult();

        // 使用 Map 将错误信息按字段分类
        Map<String, List<String>> fieldErrorsMap = bindingResult.getFieldErrors().stream()
                .collect(Collectors.groupingBy(
                        FieldError::getField,
                        Collectors.mapping(FieldError::getDefaultMessage, Collectors.toList())
                ));

        // 按字段排序
        List<String> orderedErrors = new ArrayList<>();

        // 定义字段排序的优先级
        List<String> fieldOrder = Arrays.asList("code", "name", "parentCode", "pageNum", "pageSize");

        for (String field : fieldOrder) {
            List<String> messages = fieldErrorsMap.get(field);
            if (messages != null) {
                orderedErrors.addAll(messages);
            }
        }

        // 处理未在字段排序列表中的错误
        fieldErrorsMap.forEach((field, messages) -> {
            if (!fieldOrder.contains(field)) {
                orderedErrors.addAll(messages);
            }
        });

        return RestApiResponse.error(String.join(", ", orderedErrors));
    }



    @ExceptionHandler(Exception.class)
    public ResponseInfo otherExceptionHandler(HttpServletResponse response, Exception ex) {
        response.setStatus(500);
        logger.error(ex.getMessage(), ex);
        return new ResponseInfo(500 + "", "接口异常，请联系管理员");
    }
}
